package com.niknik.woody.utils.wunit.log;

import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import static java.text.MessageFormat.format;

final class CoreLogger
    implements WLogger {

  static final Level METHOD_CALL_LEVEL = Level.FINEST;
  static final Level EX_CREATE_LEVEL = Level.FINER;
  static final Level ERR_CATCH = Level.FINE;
  static final Level FATAL_CATCH = Level.SEVERE;

  private Logger javaLogger;

  CoreLogger(Class<?> clazz) {
    javaLogger = Logger.getLogger(clazz.getName());
  }

  @Override
  public void methodCall(String msg, String... params) {
    doLog(METHOD_CALL_LEVEL, null, "METHOD_CALL", msg, params);
  }

  @Override
  public void exThrow(Throwable ex) {
    doLog(EX_CREATE_LEVEL, ex, "EXCEPTION_THROW", ex.getMessage());
  }

  @Override
  public void exCatch(Throwable ex) {
    doLog(ERR_CATCH, ex, "RECOVERABLE_EXCEPTION_CATCHING", ex.getMessage());
  }

  @Override
  public void fatalExCatch(Throwable ex, String msg, String... params) {
    doLog(FATAL_CATCH, ex, "FATAL_EXCEPTION_CATCHING", msg, params);
  }

  private void doLog(Level level, Throwable ex, String methodName, String msg, String... params) {
    if (!javaLogger.isLoggable(level)) {
      return;
    }

    LogRecord record = new LogRecord(level, msg == null
        ? null
        : format(msg, params));
    record.setThrown(ex);
    record.setSourceClassName(null);
    record.setLoggerName(javaLogger.getName());
    record.setSourceMethodName(methodName);

    javaLogger.log(record);
  }
}
